<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="电影名">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="电影类型">
      <el-select
          v-model="form.type"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="5"
          placeholder="Select"
          style="width: 240px"
      >
        <el-option
            v-for="item in type_options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="电影日期">
      <el-col :span="11">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="请选择一个日期"
            style="width: 100%"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="电影评分">
      <el-rate v-model="form.score" allow-half :max="10" disabled
               show-score
               text-color="black"
               score-template="{value} points"/>
      <el-input-number v-model="form.score" :precision="2" :step="0.1" :min="0" :max="10" style="margin-left: 10px"/>
    </el-form-item>
    <el-form-item label="电影时长">
      <el-input-number v-model="form.length" :min="1" :max="180" />
    </el-form-item>
    <el-form-item label="允许评论">
      <el-switch v-model="form.comment" />
    </el-form-item>
    <el-form-item label="允许点赞">
      <el-switch v-model="form.like" />
    </el-form-item>
    <el-form-item label="允许收藏">
      <el-switch v-model="form.stars" />
    </el-form-item>
    <el-form-item label="允许喜欢">
      <el-switch v-model="form.love" />
    </el-form-item>
    <el-form-item label="要求等级">
      <el-radio-group v-model="form.level">
        <el-radio value="0">非会员</el-radio>
        <el-radio value="1">普通会员</el-radio>
        <el-radio value="2">超级会员</el-radio>
        <el-radio value="3">super会员</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="简介">
      <el-input v-model="form.desc" type="textarea" />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="form.status" placeholder="请选择电影状态">
        <el-option label="启用" value="online" />
        <el-option label="禁用" value="offline" />
        <el-option label="隐藏" value="hide" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <view class="btn-items">
        <el-upload
            :action="fanart_uploadUrl"
            :http-request="fanart_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传fanart</el-button>
        </el-upload>

        <el-upload
            :action="poster_uploadUrl"
            :http-request="poster_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传poster</el-button>
        </el-upload>

        <el-upload
            :action="video_uploadUrl"
            :http-request="video_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload_video"
        >
          <el-button size="small" type="primary">上传视频</el-button>
        </el-upload>
      </view>

    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存修改</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted, watch} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import {md5} from "js-md5";
import { defineProps } from 'vue';
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

const props = defineProps({
  MID: String,
  cancel: Boolean,
});

// 表单的响应式数据
const form = reactive({
  name: '',
  status: '',
  date: '',
  level: '',
  desc: '',
  like: true,
  comment: true,
  love: true,
  stars: true,
  score: 10,
  type:[],
  MID:'',
  length:0,
})

// 类型选择的选项
const type_options = [
  { value: '冒险', label: '冒险' },
  { value: '动画', label: '动画' },
  { value: '喜剧', label: '喜剧' },
  { value: '家庭', label: '家庭' },
  { value: '剧情', label: '剧情' },
  { value: '奇幻', label: '奇幻' },
  { value: '科幻', label: '科幻' },
  { value: '爱情', label: '爱情' },
  { value: '悬疑', label: '悬疑' },
]

// 上传相关的数据和方法
const fanart_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_fanart' // 替换为你的上传地址
const poster_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_poster' // 替换为你的上传地址
const video_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_video' // 替换为你的上传地址
const video_addUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=edit_video' // 替换为你的上传地址

const fanart_uploadFile = async ({ file }) => {
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('data', file)
  formData.append('MID', form.MID)
  formData.append('name', form.name)
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(fanart_uploadUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] === 'success')
      {

        ElMessage.success('上传成功！')
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
    } else {
      ElMessage.error('上传失败！')
    }
  } catch (error) {
    ElMessage.error('上传失败！')
  }
  closeFullScreen(loading)
}

const poster_uploadFile = async ({ file }) => {
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('data', file)
  formData.append('MID', form.MID)
  formData.append('name', form.name)
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(poster_uploadUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] === 'success')
      {
        ElMessage.success('上传成功！')
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
    } else {
      ElMessage.error('上传失败！')
    }
  } catch (error) {
    ElMessage.error('上传失败！')
  }
  closeFullScreen(loading)
}

const video_uploadFile = async ({ file }) => {
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('data', file)
  formData.append('MID', form.MID)
  formData.append('name', form.name)
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(video_uploadUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] === 'success')
      {
        ElMessage.success('上传成功！')
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
    } else {
      ElMessage.error('上传失败！')
    }
  } catch (error) {
    ElMessage.error('上传失败！')
  }
  closeFullScreen(loading)
}
const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt3M = file.size / 1024 / 1024 < 3;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 格式!');
  }
  if (!isLt3M) {
    ElMessage.error('上传图片大小不能超过 3MB!');
  }
  return isJPG && isLt3M;
};

const beforeUpload_video = (file) => {
  const isMP4 = file.type === 'video/mp4';
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isMP4) {
    ElMessage.error('上传视频只能是 MP4 格式!');
  }
  if (!isLt50M) {
    ElMessage.error('上传视频大小不能超过 50MB!');
  }
  return isMP4 && isLt50M;
};

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()
  // const { name, status, date, level, desc, like, comment, love, stars, score, type, MID, length } = toRefs(form);
  formData.append('key', localStorage.getItem('key'));
  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? 'true' : 'false');
    }
  });

  formData.append('type', form.type); // 直接添加 form.type 的值
  formData.append('date', form.date); // 直接添加 form.type 的值
  formData.set("MID",md5(form.name));
  try {
    const response = await fetch(video_addUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('修改成功！')
        emit('close-dialog')
        // this.$emit('close-dialog');
      }
      else if (result['status'] === 'danger') {
        emit('close-dialog')
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  closeFullScreen(loading)
}
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const fetchMovieData = async (MID) => {
  try {
    const response = await fetch('https://movie.cpb2013.top/movie_info.php?MID='+MID);
    const responseData = await response.json();
    if (responseData.status === 'ok') {
      const movies = responseData.data.map((movie) => ({
        MID: movie.MID,
        fanart: movie.fanart,
        type: movie.type.split(','),
        length:parseInt(movie.length),
        name: movie.name,
        status: movie.status,
        level: movie.level,
        desc: movie.review,
        play_count: movie.play_count,
        date: movie.update_time,
        Allow_like: movie.Allow_like,
        Allow_stars: movie.Allow_stars,
        Allow_love: movie.Allow_love,
        Allow_comment: movie.Allow_comment,
        score:parseFloat(movie.score),
      }));

      if (movies.length > 0) {
        Object.assign(form, movies[0]);
      }

    } else {
      console.error('Error fetching movie data:', responseData.message);
    }
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  fetchMovieData(props.MID);
});

watch(() => props.MID, (newMID) => {
  fetchMovieData(newMID);
});

</script>
